package com.yeyks.wxcode.controller;

import com.yeyks.base.Arguments;
import com.yeyks.model.Ajax.AjaxResponseBody;
import com.yeyks.wxcode.config.WxConfig;
import com.yeyks.wxcode.service.WxLoginService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author fuchangshuai
 * @date 2019/4/27 10:25 AM
 */
@Controller
@Slf4j
public class WXMpController {

    @Autowired
    WxMpService wxMpService;
    @Autowired
    private WxLoginService wxLoginService;
    @Autowired
    private WxConfig wxConfig;
    @Value("${wx.app.redirectUri}")
    String redirectUri;

    /**
     * 引导用户进入授权页面同意授权，获取code
     *
     * @return
     */
    @ApiIgnore
    @CrossOrigin
    @GetMapping("/wechat/authorize")
    public String getWxMpCode(@RequestParam(name = "returnUrl") String returnUrl,
                              @RequestParam(name = "type", defaultValue = "gzh") String type) {
        if (returnUrl != null) {
            returnUrl = URLEncoder.encode(returnUrl);
        }
        if ("xcx".equals(type)) {
            Map<String, String> map = wxConfig.getWxModel(type);
            WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
            config.setAppId(map.get("appId"));
            config.setSecret(map.get("appSecret"));
            wxMpService.setWxMpConfigStorage(config);
        }
        String baseUrl = wxMpService.oauth2buildAuthorizationUrl(
                redirectUri,
                WxConsts.OAuth2Scope.SNSAPI_BASE,
                returnUrl);
        log.info("baseUrl打印：{}", baseUrl);
        return "redirect:" + baseUrl;
    }

    /**
     * 获取用户信息 openid 、accessToken等
     *
     * @param code
     * @param state
     * @return
     */
    @ApiIgnore
    @RequestMapping("/callback")
    public String testGetUser(String code, String state) {
        WxMpOAuth2AccessToken accessToken = new WxMpOAuth2AccessToken();
        try {
            accessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        String openId = accessToken.getOpenId();
        log.info("授权成功：" + openId);
        if (Arguments.notEmpty(state) && state.contains("?")) {
            return "redirect:" + state + "&openId=" + openId;
        } else {
            return "redirect:" + state + "?openId=" + openId;
        }
    }

    /**
     * 微信JS_SDK支持
     *
     * @return
     */
    @ApiIgnore
    @ResponseBody
    @PostMapping("/js/sdk")
    public ResponseEntity<?> jsSdk(@RequestParam(name = "url") String url) {
        try {
            WxJsapiSignature wxJsapiSignature = wxMpService.createJsapiSignature(url);
            String getJsapiTicket = wxMpService.getJsapiTicket();
            return ResponseEntity.ok(AjaxResponseBody.success(wxJsapiSignature));
        } catch (WxErrorException e) {
            e.printStackTrace();
            return ResponseEntity.ok(AjaxResponseBody.success(null));
        }
    }

    /**
     * 小程序获取openid
     *
     * @param code
     * @return
     */
    @ApiIgnore
    @PostMapping("/xcx/openid")
    @ResponseBody
    public ResponseEntity<?> xcxOpenid(@RequestParam(name = "code") String code) {
        if (code == null || code.trim().equals("")) {
            return null;
        }
        String type = "xcx";
        return ResponseEntity.ok(AjaxResponseBody.success(wxLoginService.getOpenId(code, type)));
    }

}
